package com.makao.controller;

import java.net.URI;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;

@RestController
public class Controller {
	@Autowired
	private DiscoveryClient discoveryClient2;
	
	public String getWord(String service) {
        List<ServiceInstance> list = discoveryClient2.getInstances(service);
        if (list != null && list.size() > 0 ) {
            URI uri = list.get(0).getUri();
            if (uri !=null ) {
                return (new RestTemplate()).getForObject(service,String.class);
            }
        }
        return null;
    }
    
    @RequestMapping("/sentence2")
    public  String getSentence2() {
        return
                getWord("cloud-eureka-client-subject") + " "
                        + getWord("cloud-eureka-client-verb") + " "
                        + getWord("cloud-eureka-client-object") + "."
                ;//大小写不区分
    }
    
    @Autowired
    private LoadBalancerClient client;
    
    @RequestMapping("/sentence")
    public  String getSentence() {
        return
                getWord2("cloud-eureka-client-subject") + " "
                       // + getWord2("cloud-eureka-client-verb") + " "
                       // + getWord2("cloud-eureka-client-object") + "."
                ;//大小写不区分
    }
    
    public String getWord2(String service) {
        ServiceInstance instance = client.choose(service);//这里会根据application.yml中的负载均衡设置去选择service对应的机器来提供服务；第二种方法就是现在使用的代码的方式@RibbonClient和@Configuration结合
        URI uri = instance.getUri();
        System.out.println("service from: "+uri);//默认情况下是轮询的负载均衡，在服务的多个节点上轮流提供服务。
        return (new RestTemplate()).getForObject(uri,String.class);
    }
}